﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace zielonka.co.uk.extensions.system.io
{
    // Description:	Set the stream position to the place where for example 10 lines will be returned when read to end.
    /*
        var s = File.OpenFile("text.txt");
        s.Tail(10);
     */

    public static partial class StreamExtensions
    {       
        /// <summary>
        /// Set position to return n number of lines
        /// </summary>
        /// <param name="this"></param>
        /// <param name="n">number of lines</param>
        /// <returns>The stream with position set</returns>
        public static Stream Tail(this Stream @this, int n)
        {
            if (@this.Length == 0)
                return @this;
            @this.Seek(0, SeekOrigin.End);
            var count = 0;
            while (count <= n)
            {
                @this.Position--;
                var c = @this.ReadByte();
                @this.Position--;
                if (c == '\n')
                {
                    ++count;
                }
                if (@this.Position == 0)
                    break;
            }
            return @this;
        }
    }
}
